from sklearn.datasets import fetch_mldata
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

#读取数据
mnist = fetch_mldata('mnist-original',data_home='./')
x,y = mnist['data'],mnist['target']
x_train,x_test,y_train,y_test = x[:60000,:],x[60000:,:],y[:60000],y[60000:]

# 划分训练集测试集
#训练集洗牌赋值
shuffer_index = np.random.permutation(60000)
x_train,y_train = x_train[shuffer_index],y_train[shuffer_index]
#测试集洗牌赋值
shuffer_index = np.random.permutation(10000)
x_test,y_test = x_test[shuffer_index],y_test[shuffer_index]
# 选择标签
some_digit = x_train[7777]
# some_digit_img = some_digit.reshape(28,28)
# plt.imshow(some_digit_img,cmap=matplotlib.cm.binary)
# plt.show()

#选择模型
# 拿出标签为7的标签
y_train_7 = (y_train == 7)
# 算出距离
# knf = KNeighborsClassifier()
# knf.fit(x_train,y_train_7)
some_digit = [some_digit]
# 预测数据
# print(knf.predict(some_digit))

#网格搜索
# grid_params = [{'weights':['umiform','distance'],'n_neighbors':[3,4,5]}]
knnf = KNeighborsClassifier(n_jobs=3,weights='uniform')
knnf.fit(x_train,y_train)
# grid_search = GridSearchCV(knnf,grid_params,cv=5,verbose=3,n_jobs=1)
# grid_search.fit(x_train,y_train)
# print(grid_search.best_params_)
# print(grid_search.best_score_)

#测试集验证
y_pred = knnf.predict(x_test)
print(accuracy_score(y_test,y_pred))